import { loginAPI, getUserInfoAPI } from '@/api/user'
import { getTokenCookie, removeTokenCookie, setTokenCookie } from '@/utils/auth'
import { resetRouter } from '@/router'

const state = {
  token: getTokenCookie() || null, // 用户登录令牌
  userInfo: {} // 用户信息
}

const mutations = {
  // 设置token
  setToken(state, newToken) {
    state.token = newToken
    setTokenCookie(newToken)
  },
  // 删除token
  removeToken(state) {
    state.token = null
    removeTokenCookie()
  },
  // 设置用户信息
  setUserInfo(state, newInfo) {
    state.userInfo = newInfo
  }
}

const actions = {
  // 登录请求
  async login(context, { mobile, password }) {
    // 发起登录请求
    const token = await loginAPI({ mobile, password })
    // 设置token
    context.commit('setToken', token)
  },
  // 退出登录
  async logout(context) {
    // 删除token
    context.commit('removeToken')
    // 删除用户信息
    context.commit('setUserInfo', {})
    resetRouter()
  },
  // 获取用户信息
  async getUserInfo(context) {
    // 发起请求
    const res = await getUserInfoAPI()
    // 设置用户信息
    context.commit('setUserInfo', res)
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
